﻿@page "/plc"
@rendermode InteractiveServer

<PageTitle>Plc</PageTitle>

<h1>Plc Demo</h1>

<div class="container mt-5">
    <div class="row">
        <div class="col-md-6">
            <h2>Read Section</h2>
            <div class="input-group mb-3">
                <input type="text" @bind-value="ReadAddress" class="form-control" id="readInput" placeholder="Enter text to read">
                <button class="btn btn-primary" type="button" id="readButton" @onclick="ReadData">读取</button>
            </div>
        </div>
        <div class="col-md-6">
            <h2>Write Section</h2>
            <div class="input-group mb-3">
                <input type="text" @bind-value="WriteAddress" class="form-control" id="writeInput" placeholder="写入地址：例如DB0.BH0.0">
                <input type="text" @bind-value="WriteValue" class="form-control" id="writeInput" placeholder="写入数据">
                <button class="btn btn-primary" type="button" id="writeButton" @onclick="RwiteData">写入</button>
            </div>
        </div>
    </div>
    <div class="row mt-4">
        <div class="col-12">
            <h2>日志</h2>
            <div class="border p-3" style="height: 200px; overflow-y: auto;" id="logOutput">
                <ul>
                    @foreach  (var msg in messages)
                    {
                        <li>@msg</li>
                    }
                </ul>
            </div>
        </div>
    </div>
</div>



@code {


    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    int currentCount = 0;

    List<string> messages = new();
    string ReadAddress = "";
    string WriteAddress = "";
    string WriteValue = "";
    S7.Net.Plc plc;





    private void log(string msg)
    {
        messages.Add(msg);
        // StateHasChanged();
    }

    private void ReadData()
    {
        var ret = plc.Read(ReadAddress);
        log("读取数据[" + ReadAddress + "] = "+ ret.ToString());
    }

    private void RwiteData()
    {
        plc.Write(WriteAddress, short.Parse(WriteValue));
        log("写入数据[" + WriteAddress + "]" + "=> " + WriteValue);
    }

    protected override async Task OnInitializedAsync()
	{

		plc = new(S7.Net.CpuType.S71200, "192.168.30.90", 0, 1);
		plc.Open();
		log("connected");

	}

}
